<template>
  <div>
    <div ref="bpmnContainer" class="bpmn-container"></div>
    <!-- <a-button @click="highlightNode">高亮审批节点</a-button>
    <a-button @click="clearAllMarkers">重置高亮节点</a-button> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import createDefaultBpmnXml from "@/components/Camunda/Bpmn/src/defaultBpmnXml";
import Modeler from "bpmn-js/lib/Modeler";
import translate from "@/components/Camunda/Bpmn/src/zh/index";
import GridLineModule from "diagram-js-grid-bg";
import { debounce } from "lodash-es";
import systask from "@/api/wms-system/systask";
const bpmnContainer = ref<HTMLDivElement | null>(null);
defineExpose({
  highlightNode,
  clearAllMarkers,
});

const props = withDefaults(
  defineProps<{
    detailId: any;
  }>(),
  {
    detailId: () => null,
  }
);
// 创建bpmnViewer实例
let bpmnViewer: any = null;
onMounted(async () => {
  bpmnViewer = new Modeler({
    container: bpmnContainer.value as HTMLDivElement,
    additionalModules: [
      {
        translate: ["value", translate()],
        paletteProvider: ["value", ""],
        labelEditingProvider: ["value", ""],
        contextPadProvider: ["value", ""],
        bendpoints: ["value", {}],
        move: ["value", ""],
      },
      GridLineModule,
    ],
    gridLine: {
      smallGridSpacing: 20,
      gridSpacing: 80,
      gridLineStroke: 1,
      gridLineOpacity: 0.2,
      gridLineColor: "#ddd",
    },
  });
  // const xml = createDefaultBpmnXml("process_1", "diagram_1", "");
  // loadDiagram(xml);
  const { backData, result } = await systask.detailFlow({
    id: props.detailId,
  })();
  if (result) {
    loadDiagram(backData.data.content);
  }
});

// watch(
//   () => props.detailId,
//   async (val) => {
//     if (val) {
//       const { backData, result } = await systask.detailFlow({
//         id: props.detailId,
//       })();
//       if (result) {
//         loadDiagram(backData.data.content);
//       }
//     }
//   },
//   { immediate: true, deep: true }
// );

async function loadDiagram(xml: string): Promise<void> {
  try {
    await bpmnViewer?.importXML(xml);
    bpmnViewer?.get("canvas").zoom("fit-viewport", { animate: true });
    //给任务节点加聚焦和离焦事件
    bindEvents();
  } catch (err) {
    console.error("加载BPMN图错误：", err);
  }
}

// 已成功的节点 ID 列表
const OkIdList = ref<string[]>(["Event_178kjur"]);
// 正在处理的节点 ID 列表
const processingIdList = ref<string[]>(["Activity_108ybh5"]);

function clearAllMarkers(): void {
  const canvas = bpmnViewer?.get("canvas");
  const elementRegistry = bpmnViewer?.get("elementRegistry");
  elementRegistry?.getAll().forEach((element) => {
    canvas?.removeMarker(element.id, "OkHighlight");
    canvas?.removeMarker(element.id, "highlight");
  });
}

// 汇总节点需要
function highlightNode(): void {
  // const canvas = bpmnViewer?.get("canvas");
  // if (!canvas) return;
  // clearAllMarkers();
  // OkIdList.value.forEach((elementId: string) => {
  //   canvas.addMarker(elementId, "OkHighlight");
  // });
  // processingIdList.value.forEach((elementId: string) => {
  //   canvas.addMarker(elementId, "highlight");
  // });
}
const MapType = {
  "bpmn:ExclusiveGateway": "网关",
};
//某些节点不显示悬浮框
const ExcludedNodeList = ref<string[]>([
  "bpmn:Process",
  "label",
  "bpmn:SequenceFlow",
]);
function bindEvents() {
  let eventBus = bpmnViewer.get("eventBus");
  let overlays = bpmnViewer.get("overlays");
  // 防抖处理函数（300ms间隔）
  const handleHover = debounce((e) => {
    const element = e?.element;
    if (!element || !element.businessObject) return;

    const excludedList = ExcludedNodeList.value;
    if (excludedList.includes(element.type)) return;

    const bo = element.businessObject;
    const name = bo.name || MapType[bo.$type] || "未命名节点";
    const id = element.id;

    const overlayHtml = `
      <div style="
        background: white;
        border: 1px solid #ccc;
        padding: 8px;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        min-width: 120px;
      ">
        <div>${name}</div>
        <div style="color: #666; font-size: 0.8em">ID: ${id}</div>
      </div>
    `;

    overlays.add(element.id, {
      position: { top: -20, right: 0 },
      html: overlayHtml,
      show: { minZoom: 0.5 },
    });
  }, 300); // 防抖时间可根据实际需求调整
  eventBus.on("element.hover", (e) => {
    // 先清除已有悬浮层
    overlays.remove({ element: e.element });
    // 触发防抖处理
    handleHover(e);
  });

  eventBus.on("element.out", (e) => {
    // 立即执行清除操作
    handleHover.cancel(); // 取消未执行的防抖操作
    overlays.remove({ element: e.element });
    overlays.clear();
  });
}
</script>
<style>
/* 待处理节点高亮样式 */
.highlight:not(.djs-connection) .djs-visual > :nth-child(1) {
  stroke: #ffa500 !important; /* 橙色边框 */
  stroke-width: 2px !important;
  filter: drop-shadow(0 0 4px rgba(255, 165, 0, 0.6)); /* 发光效果 */
}
/* 已处理节点高亮样式 */
.OkHighlight:not(.djs-connection) .djs-visual > :nth-child(1) {
  stroke: rgba(0, 255, 4, 1) !important; /* 橙色边框 */
  stroke-width: 2px !important;
  filter: drop-shadow(0 0 4px rgba(0, 255, 4, 0.6)); /* 发光效果 */
}
.layer-selectionOutline {
  display: none;
}
.bpmn-container {
  height: 600px;
  border: 1px solid #ccc;
  margin-bottom: 20px;
}
</style>
